package com.xrtn.service.impl;

import com.xrtn.bean.*;
import com.xrtn.mapper.*;
import com.xrtn.page.Page;
import com.xrtn.service.ICommonService;
import com.xrtn.utils.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by tu_pei on 2018/2/27.
 */
@Service
public class CommonServiceImpl implements ICommonService {

    /**
     * 患者信息对象
     */
    @Autowired
    private TPatientInfoMapper patientInfoMapper;
    /**
     * 基础调查信息表对象
     */
    @Autowired
    private TPatientInitMapper patientInitMapper;
    /**
     * 患者历史病历档案对象
     */
    @Autowired
    private TPatientHistoryMapper patientHistoryMapper;
    /**
     * 订单信息表对象
     */
    @Autowired
    private TOrderInfoMapper orderInfoMapper;
    /**
     * 病症类型表
     */
    @Autowired
    private InitDiseaseTypeMapper diseaseTypeMapper;
    /**
     * 病症信息表
     */
    @Autowired
    private InitDiseaseInfoMapper diseaseInfoMapper;
    /**
     * 穴位信息表
     */
    @Autowired
    private InitPointInfoMapper pointInfoMapper;
    /**
     * 穴位类型表
     */
    @Autowired
    private InitPointTypeMapper pointTypeMapper;
    /**
     * 推拿服务表
     */
    @Autowired
    private InitServiceInfoMapper initServiceInfoMapper;

    /**
     * 药品信息表
     */
    @Autowired
    private InitGoodsInfoMapper initGoodsInfoMapper;
    /**
     * 请假信息表
     */
    @Autowired
    private TOffInfoMapper offInfoMapper;
    /**
     * 门店信息表
     */
    @Autowired
    private TSubclinicInfoMapper subclinicInfoMapper;
    /**
     * 后台用户信息表
     */
    @Autowired
    private SysUserInfoMapper sysUserInfoMapper;
    /**
     * 预约信息表
     */
    @Autowired
    private TBookingInfoMapper bookingInfoMapper;

    @Autowired
    private TUserInfoMapper userInfoMapper;

    @Autowired
    private TCouponUsrRelMapper couponUsrRelMapper;
    @Autowired
    private SysDiscountCardInfoMapper discountCardInfoMapper;
    @Autowired
    private SysAccountCardInfoMapper accountCardInfoMapper;
    @Autowired
    private InitConclusionInfoMapper conclusionInfoMapper;
    @Autowired
    private TDoctorPushRelMapper doctorPushRelMapper;

    @Autowired
    private TPatientTreatmentMapper patientTreatmentMapper;

    @Autowired
    private AccountUserInfoMapper accountUserInfoMapper;
    /**
     * 商品消耗统计表
     */
    @Autowired
    private TOrderGoodsDetailMapper orderGoodsDetailMapper;

    @Autowired
    private TBackcardInfoMapper backcardInfoMapper;
    @Autowired
    private TUserDiseaseRelMapper userDiseaseRelMapper;
    @Autowired
    private TUserTreatmentRelMapper userTreatmentRelMapper;
    @Autowired
    private TUserNersingRelMapper nersingRelMapper;

    @Autowired
    private TCardUsrRelMapper cardUsrRelMapper;
    @Autowired
    private InitGradeDoctorMapper gradeDoctorMapper;

    @Autowired
    private InitFromInfoMapper initFromInfoMapper;

    @Autowired
    private TDegreeInfoMapper degreeInfoMapper;

    @Autowired
    private InitLabelInfoMapper labelInfoMapper;

    @Autowired
    private SysRoleInfoMapper roleInfoMapper;

    @Autowired
    private UserCodeMapper userCodeMapper;

    @Autowired
    private TUserConclusionRelMapper userConclusionRelMapper;

    @Autowired
    private TUserPointRelMapper userPointRelMapper;

    @Autowired
    private AccountOrderInfoMapper accountOrderInfoMapper;

    @Autowired
    private TOrderGoodsDetailMapper goodsDetailMapper;

    @Autowired
    private TOrderServiceDetailMapper serviceDetailMapper;

    @Override
    public Map<String, Object> selectSysDesktop(Map<String, Object> params) {

        Map<String, Object> retMap = new HashMap<>();

        //主营收入  ||  付款订单

        Map<String, Object> orderMap = orderInfoMapper.selectOrderStatistics(params);

        if (ObjUtils.isNotEmpty(orderMap)) {
            //主营收入
            retMap.put("orderCost", orderMap.get("orderCost"));
            //付款订单
            retMap.put("orderNumber", orderMap.get("orderNumber"));
        } else {
            //主营收入
            retMap.put("orderCost", 0);
            //付款订单
            retMap.put("orderNumber", 0);
        }
        //余额消费  ||  耗卡消费
        params.put("accountType", 1);
        List<Map<String, Object>> accountMap = accountUserInfoMapper.selectSumCost(params);

        if (accountMap.size() > 0) {
            //余额
            retMap.put("accountCost", accountMap.get(0).get("cost"));
        } else {
            //充值金额
            retMap.put("accountCost", 0);
        }

        //耗卡金额 =
        //retMap.put("cardCost", accountMap.get(1).get("cost"));
        //余额支付
        Map<String, Object> balance = orderInfoMapper.selectUserToDayOrderMoney(params);

        retMap.put("cardCost", balance.get("orderTotalCost"));

        //到店人数  ||  预约单数
        params.put("createTime", new Date());
        //params.put("bookingStatus", "0");

        Integer unPayNumber = 0;
        List<TBookingInfo> bookingInfoList2 = bookingInfoMapper.selectByMap2(params);
        if (bookingInfoList2.size() > 0) {
            retMap.put("bookingNumber", bookingInfoList2.size());
            for (TBookingInfo bookingInfo : bookingInfoList2) {
                if (bookingInfo.getBookingStatus() == 3) {
                    unPayNumber++;
                }
            }
        }
        retMap.put("toDayOrderNumber", unPayNumber);

        List<TBookingInfo> bookingInfoList = bookingInfoMapper.selectByMap(params);
        if (bookingInfoList.size() > 0) {
            //到店人数
            Integer arriveNumber = 0, unBookingNumber = 0;
            //预约单数
            retMap.put("bookingNumber", bookingInfoList.size());
            for (TBookingInfo bookingInfo : bookingInfoList) {
                //当前状态:0:待就诊;1:已迟到;2:调理中;3:待支付;4:已完成;5:取消;6:已接诊
                if (bookingInfo.getBookingStatus() == 2 || bookingInfo.getBookingStatus() == 3 ||
                        bookingInfo.getBookingStatus() == 4 || bookingInfo.getBookingStatus() == 6) {
                    //到店人数
                    arriveNumber++;
                }
                if (bookingInfo.getBookingStatus() == 0) {
                    unBookingNumber++;
                }
            }
            retMap.put("unBookingNumber", unBookingNumber);
            retMap.put("arriveNumber", arriveNumber);
//            retMap.put("toDayOrderNumber", 0);
        } else {
            retMap.put("bookingNumber", 0);
            retMap.put("arriveNumber", 0);
//            retMap.put("toDayOrderNumber", 0);
        }

        //新增会员
        List<TUserInfo> userList = userInfoMapper.selectByMap(params);
        //商品消耗
        List<TOrderGoodsDetail> goodsList = orderGoodsDetailMapper.selectByMap(params);
        //新增会员
        retMap.put("userNumber", userList.size());
        //商品消耗
        Integer goodsNum = 0;

        for (TOrderGoodsDetail goods : goodsList) {
            goodsNum += goods.getOrderNum();
        }

        retMap.put("goodsNumber", goodsNum);

        // 查询今日退单数量
        params.put("isBack", 0);
        params.put("createTime", null);
        List<TBackcardInfo> backcardInfos = backcardInfoMapper.selectByMapList(params);
        if (backcardInfos.size() > 0) {
            retMap.put("toDayBackOrderNumber", backcardInfos.size());
        } else {
            retMap.put("toDayBackOrderNumber", 0);
        }
        return retMap;
    }

    /**
     * 保存用户
     *
     * @param userInfo
     * @return
     */
    @Override
    public Integer saveUserInfo(TUserInfo userInfo) {
        Map<String, Object> selectMap = new HashMap<>();
        selectMap.put("userPhone", userInfo.getUserPhone());
        List<TUserInfo> userList = userInfoMapper.selectByMap(selectMap);

        if (userList.size() > 0) {
            return 0;
        }
        userInfoMapper.insertSelective(userInfo);
        return userInfo.getUserId();
    }

    /**
     * 修改
     *
     * @param userInfo
     * @return
     */
    @Override
    public Integer updateUserInfo(TUserInfo userInfo) {
        Map<String, Object> params = new HashMap<>();
        if (ObjUtils.isNotEmpty(userInfo.getUserId())) {
            params.put("userId", userInfo.getUserId());
        }

        List<TUserInfo> userList = userInfoMapper.selectByMap(params);
//        int uId = 0 , userId = userInfo.getUserId(); // TreeJohn 永远不可以return 0
//        if( userList.size() > 0 ){
//            //修改信息
//            uId = userList.get(0).getUserId();
//            if(userId != uId){
//                return 0;
//            }
//        }

        if (userList.size() > 0) {
            String newUserPhone = userInfo.getUserPhone();
            String oldUserPhone = userList.get(0).getUserPhone();
            if (!oldUserPhone.equals(newUserPhone)) {
                List<TUserInfo> phoneUserList = userInfoMapper.selectByPhoneInfo(newUserPhone);
                if (phoneUserList.size() > 0) {
                    return -3;
                }
            }
        }

        params.put("userPhone", userList.get(0).getUserPhone());
        UserCode userCode = userCodeMapper.selectItem(params);

        //校验验证码和时间
        if (ObjUtils.isNotEmpty(userInfo.getWidth())) {
            if (ObjUtils.isEmpty(userCode)) {
                return -4;
            }
            if (!userInfo.getWidth().equals(String.valueOf(userCode.getRandNum()))) {
                return -1;
            }
            long nowTime = System.currentTimeMillis() / 1000;
            Integer nowTimeInt = new Long(nowTime).intValue();
            if (nowTimeInt > (userCode.getCreateTime() + 60 * 10)) {
                return -2;
            }
        }

        //解绑第二，第三联系人
        if (ObjUtils.isNotEmpty(userInfo.getUserPhones()) || ObjUtils.isNotEmpty(userInfo.getUserPhoness())) {

            params = new HashMap<>();

            List<TUserInfo> userLists = new ArrayList<>();

            if (ObjUtils.isNotEmpty(userInfo.getUserPhones())) {
                //判断第二联系人，
                if (userInfo.getUserPhones().equals("空")) {
                    //解绑，
                    userInfo.setUserPhones("");
                } else {
                    //
                    params.put("userPhone", userInfo.getUserPhones());
                    userLists = userInfoMapper.selectByMap(params);
                    if (userLists.size() > 0) {
                        return 0;
                    }
                }
            } else {

                if (userInfo.getUserPhoness().equals("空")) {
                    userInfo.setUserPhoness("");
                } else {
                    params.put("userPhone", userInfo.getUserPhoness());
                    userLists = userInfoMapper.selectByMap(params);
                    if (userLists.size() > 0) {
                        return 0;
                    }
                }
            }
        }

        return userInfoMapper.updateByPrimaryKeySelective(userInfo);
    }

    /**
     * @param userId
     * @return
     */
    @Override
    public TUserInfo updateUserSendCode(Integer userId, String userPhone) {

        String code = ObjUtils.randomNumeric(6);

        TUserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);

        if (ObjUtils.isEmpty(userInfo)) {
            return null;
        }
        int userIds = userId;
        Map<String, Object> params = new HashMap<>();
        params.put("userPhone", userPhone);
        List<TUserInfo> user = userInfoMapper.selectByMap(params);
        if (user.size() > 0) {
            int uId = user.get(0).getUserId();
            if (uId == userIds) {
                //解绑
            } else {
                //绑定，
                return null;
            }
        }

        if (ObjUtils.isEmpty(userInfo)) {
            return null;
        }
        SendValidataCode.sendSms(userInfo.getUserPhone(), "259860", code);

        userInfo.setWidth(code);
        try {
            long nowTime = System.currentTimeMillis() / 1000;
            Integer nowTimeInt = new Long(nowTime).intValue();
            UserCode userCode = new UserCode();
            userCode.setCreateTime(nowTimeInt);
            userCode.setUserPhone(userInfo.getUserPhone());
            userCode.setRandNum(Integer.parseInt(code));

            userCodeMapper.addItem(userCode);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return userInfo;
    }

    /**
     * 查询患者
     *
     * @param userId
     * @return
     */

    @Override
    public List<TPatientInfo> selectPatientListByUserId(Integer userId) {
        return patientInfoMapper.selectByUserId(userId);
    }

    /**
     * 修改预约详情
     *
     * @param bookingInfo
     * @param patientName
     * @param patientBirthday
     * @param patientGender
     * @return
     */
    @Override
    public Integer updateBookingInfo(TBookingInfo bookingInfo, String patientName, String patientBirthday, Integer patientGender) {

        TBookingInfo booking = bookingInfoMapper.selectByPrimaryKey(bookingInfo.getBookingId());

        if (ObjUtils.isEmpty(booking)) {
            return null;
        }

//        if(ObjUtils.isEmpty(bookingInfo.getPatientId())){
//            //新增患者
//            TPatientInfo patientInfo = new TPatientInfo();
//            patientInfo.setUserId(bookingInfo.getUserId());
//            patientInfo.setPatientName(patientName);
//            patientInfo.setPatientBirthday(patientBirthday);
//            patientInfo.setPatientGender(patientGender);
//
//            patientInfoMapper.insertSelective(patientInfo);
//
//            TPatientInit init = new TPatientInit();
//            init.setBookingId(booking.getBookingId());
//            init.setCreateTime(new Date());
//            init.setUserName(patientName);
//            init.setPatientId(patientInfo.getPatientId());
//            init.setUserGender(patientGender);
//            init.setUserBirthday(patientBirthday);
//            init.setUserSource("1");
//            patientInitMapper.insertSelective(init);
//        }

        if (ObjUtils.isNotEmpty(bookingInfo.getBookingType())) {

            //判断是预防保健还是调理身体
            if (bookingInfo.getBookingType() == 0) {
                //调理身体
            } else {
                //预防保健
                Map<String, Object> params = new HashMap<>();
                params.put("bookingId", booking.getBookingId());
                TPatientTreatment treatment = patientTreatmentMapper.selectByMap(params);
                if (ObjUtils.isNotEmpty(treatment)) {
                    treatment.setBookingType(bookingInfo.getBookingType());
                    treatment.setIsAdd(bookingInfo.getIsAdd());
                    treatment.setTreatmentTime(new Date());
                    treatment.setCreateTime(new Date());
                    treatment.setUserId(booking.getUserId());
                    treatment.setPatientId(booking.getPatientId());
                    treatment.setDiseaseInfo("预防保健");
                    treatment.setDiseaseTime(new Date());
                    patientTreatmentMapper.updateByPrimaryKeySelective(treatment);
                } else {
                    //新增空病例
                    treatment = new TPatientTreatment();
                    treatment.setBookingId(bookingInfo.getBookingId());
                    treatment.setTreatmentTime(new Date());
                    treatment.setIsAdd(bookingInfo.getIsAdd());
                    treatment.setBookingType(bookingInfo.getBookingType());
                    treatment.setCreateTime(new Date());
                    treatment.setUserId(booking.getUserId());
                    treatment.setPatientId(booking.getPatientId());
                    treatment.setDiseaseInfo("预防保健");
                    treatment.setDiseaseTime(new Date());
                    Map<String, Object> map = new HashMap<>();
                    map.put("bookingId", treatment.getBookingId());
                    map.put("patientId", treatment.getPatientId());
                    if (null == patientTreatmentMapper.selectByBookingIdAndPatientId(map)) {
                        patientTreatmentMapper.insertSelective(treatment);
                    }
                }
            }

        }

        bookingInfoMapper.updateByPrimaryKeySelective(bookingInfo);
        return 1;
    }

    @Override
    public TSubclinicInfo selectSubclinicInfoByKey(Integer subId) {
        return subclinicInfoMapper.selectByPrimaryKey(subId);
    }

    /**
     * 添加患者
     *
     * @param record
     * @return
     */
    @Override
    public int insertTPatientInfoSelective(TPatientInfo record) {
        patientInfoMapper.insertSelective(record);
        return record.getPatientId();
    }

    /**
     * 调查问卷表单
     *
     * @param diseaseArray
     * @return
     */
    @Override
    public int saveDiseaseList(String diseaseArray) {

        JSONArray diseaseArrays = JSONArray.fromObject(diseaseArray);

        int count = 0;

        if (diseaseArrays.size() <= 0) {
            return 0;
        }
        //diseaseScore 扣总分
        Integer diseaseScore = 0,
                treatmentId = Integer.parseInt(diseaseArrays.getJSONObject(0).get("treatmentId").toString());


        //计算治愈率
        //TUserTreatmentRel userTreatmentRel = userTreatmentRelMapper.selectTreatmentFrontInfo(treatmentId);

        TPatientTreatment treatment = patientTreatmentMapper.selectByPrimaryKey(treatmentId);

        TBookingInfo bookingInfo = bookingInfoMapper.selectByPrimaryKey(treatment.getBookingId());

        Integer doctorId = bookingInfo.getDoctorId();

        for (int i = 0; i < diseaseArrays.size(); i++) {
            JSONObject jsonObject = diseaseArrays.getJSONObject(i);
            TUserDiseaseRel diseaseInfo = new TUserDiseaseRel();
            diseaseInfo.setUserId(jsonObject.optInt("userId"));
            diseaseInfo.setBookingId(jsonObject.optInt("bookingId"));
            diseaseInfo.setPatientId(jsonObject.optInt("patientId"));
            diseaseInfo.setDoctorId(jsonObject.optInt("doctorId"));
            doctorId = jsonObject.optInt("doctorId");
            diseaseInfo.setTypeId(jsonObject.optInt("typeId"));
            diseaseInfo.setDiseaseId(jsonObject.optInt("diseaseId"));
            diseaseInfo.setTypeName(jsonObject.optString("typeName"));
            diseaseInfo.setDiseaseName(jsonObject.optString("diseaseName"));
            diseaseInfo.setIsMain(1);
            diseaseInfo.setTreatmentId(treatmentId);
            diseaseInfo.setDiseaseScore(jsonObject.optInt("diseaseScore"));
            if (diseaseInfo.getIsMain() == 1) {
                diseaseScore += (jsonObject.optInt("diseaseScore"));
            }
            count += userDiseaseRelMapper.insertSelective(diseaseInfo);
        }
        //如果第一次未填写
        //if (ObjUtils.isEmpty(userTreatmentRel)){
        TUserTreatmentRel userTreatment = new TUserTreatmentRel();
        userTreatment.setSumValue(diseaseScore);//第一次得分
        userTreatment.setTreatmentRatio(new BigDecimal(0.0));//治愈率为0
        userTreatment.setDoctorId(doctorId);
        userTreatment.setTreatmentId(treatmentId);
        count += userTreatmentRelMapper.insertSelective(userTreatment);
        //}

        //常规情况 ： 第一次是大夫在APP接诊推送给家长填写的主症评分，所以userTreatmentRel 对象不会为空，
        // 100 表示已经治愈
//        if (ObjUtils.isNotEmpty(userTreatmentRel)) {
//            if(userTreatmentRel.getSumValue() < 150){
//                userTreatmentRel.setTreatmentId(treatmentId);
//                //  治愈率 =（家长评分-上次评分）/(150-上次评分)
//                //  家长评分 ： diseaseScore
//                //  上次评分 ： userTreatmentRel.getSumValue()
//                Double dScore = ((150-Double.valueOf(diseaseScore))- userTreatmentRel.getSumValue());
//                Double tScore = 150 - Double.valueOf(userTreatmentRel.getSumValue());
//
//                Double score = dScore / tScore;
//                userTreatmentRel.setSumValue(150-diseaseScore);
//                userTreatmentRel.setTreatmentRatio(new BigDecimal(score* 100) );
//                userTreatmentRel.setDoctorId(doctorId);
//                userTreatmentRel.setRelId(null);
//                userTreatmentRel.setTreatmentId(treatmentId);
//                count += userTreatmentRelMapper.insertSelective(userTreatmentRel);
//            }else{
//                userTreatmentRel.setSumValue(150);
//                userTreatmentRel.setTreatmentRatio(new BigDecimal(1) );
//                userTreatmentRel.setDoctorId(doctorId);
//                userTreatmentRel.setRelId(treatmentId);
//                count += userTreatmentRelMapper.insertSelective(userTreatmentRel);
//            }
//        }

        return count;
    }

    /**
     * 调查问卷表单
     *
     * @param params
     * @return
     */
    @Override
    public List<TPatientInfo> selectPatient(Map<String, Object> params) {

        return patientInfoMapper.selectBySubclinicId(params);
    }

    /**
     * 添加基础调查表
     *
     * @param record
     * @return
     */
    @Override
    public int insertTPatientInitSelective(TPatientInit record) {
        //添加基础信息调查表后可进入第二阶段填写患者病历

        TPatientHistory history = patientHistoryMapper.selectByPatientId(record.getPatientId());
        if (ObjUtils.isNotEmpty(history)) {
            record.setTherapyStatus(2);
        }
        record.setCreateTime(new Date());
        return patientInitMapper.insertSelective(record);
    }

    /**
     * @param patientInit
     * @param bookingInfo
     * @param bookingName
     * @param bookingPhone
     * @param bookingPhones
     * @param patientHistory
     * @param userId
     * @return
     */
    @Override
    public Map<String, Object> insertSysTPatientInitSelective(TPatientInit patientInit, TBookingInfo bookingInfo, String bookingName, String bookingPhone,
                                                              String bookingPhones, TPatientHistory patientHistory, Integer userId) {


        TPatientInfo patientInfo = new TPatientInfo();
        patientInfo.setUserId(userId);
        patientInfo.setPatientImg(patientInit.getUserImg());
        patientInfo.setPatientGender(patientInit.getUserGender());
        patientInfo.setPatientName(patientInit.getUserName());
        patientInfo.setPatientHeight(patientInit.getUserHeight());
        patientInfo.setPatientBodyWeight(patientInit.getUserBodyWeight());
        patientInfo.setPatientBirthday(patientInit.getUserBirthday());
        patientInfo.setPatientAddress(patientInit.getUserAddress());
        patientInfo.setPatientDesc(patientInit.getUserDesc());
        patientInfo.setPatientAge(patientInit.getUserAge());

        insertTPatientInfoSelective(patientInfo);

        patientInit.setCreateTime(new Date());

        patientInit.setBookingId(bookingInfo.getBookingId());
        patientInit.setPatientId(patientInfo.getPatientId());
        insertTPatientInitSelective(patientInit);
        patientHistory.setUserId(patientInfo.getPatientId());
        insertPatientHistorySelective(patientHistory);

        Map<String, Object> retMap = new HashMap<>();

        retMap.put("patientId", patientInfo.getPatientId());

        return retMap;
    }

    /**
     * 新增患者调查记录表
     *
     * @param record
     * @return
     */
    @Override
    public int updateTPatientInitSelective(TPatientInit record) {
        record.setCreateTime(new Date());

        TPatientInit init = patientInitMapper.selectByPrimaryKey(record.getRelId());

        TPatientInfo patientInfo = patientInfoMapper.selectByPrimaryKey(init.getPatientId());

        if (ObjUtils.isNotEmpty(patientInfo)) {
            patientInfo.setPatientImg(record.getUserImg());
            patientInfo.setPatientGender(record.getUserGender());
            patientInfo.setPatientBirthday(record.getUserBirthday());
            patientInfo.setPatientName(record.getUserName());
            patientInfo.setPatientAddress(record.getUserAddress());
            patientInfo.setPatientBodyWeight(record.getUserBodyWeight());
            patientInfo.setPatientHeight(record.getUserHeight());
            patientInfo.setPatientAge(record.getUserAge());
            patientInfoMapper.updateByPrimaryKeySelective(patientInfo);
        }
        return patientInitMapper.updateByPrimaryKeySelective(record);
    }

    /**
     * 修改患者调查记录表
     *
     * @param record
     * @return
     */
    @Override
    public int updateTPatientInfoSelective(TPatientInfo record) {


//        Map<String, Object> params = new HashMap<>();
//        params.put("patientId", record.getPatientId());
//        Map<String, Object> patientMap = patientInitMapper.selectByMap(params);
//        if (ObjUtils.isNotEmpty(patientMap)) {
//            TPatientInit patientInit = new TPatientInit();
//            patientInit.setRelId(Integer.parseInt(patientMap.get("relId").toString()));
//            patientInit.setUserBirthday(record.getPatientBirthday());
//            patientInit.setUserBodyWeight(record.getPatientBodyWeight());
//            patientInit.setUserHeight(record.getPatientHeight());
//            patientInit.setUserGender(record.getPatientGender());
//            patientInit.setUserAddress(record.getPatientAddress());
//            patientInit.setUserName(record.getPatientName());
//            patientInit.setCreateTime(new Date());
//            patientInit.setUserImg(record.getPatientImg());
//            patientInitMapper.updateByPrimaryKeySelective(patientInit);
//        }

        //根据年月日计算年龄


        return patientInfoMapper.updateByPrimaryKeySelective(record);
    }

    /**
     * 查询患者调查记录表
     *
     * @param params
     * @return
     */
    @Override
    public Map<String, Object> selectTPatientInitByMap(Map<String, Object> params) {

        Map<String, Object> patientInit = patientInitMapper.selectByMap(params);

        if (ObjUtils.isNotEmpty(patientInit)) {
            List<TOrderInfo> orderInfo = orderInfoMapper.selectByMaps(params);

            if (orderInfo.size() > 0) {
                patientInit.put("patientTime", orderInfo.get(0).getOrderTime());
                patientInit.put("lastTime", orderInfo.get(0).getOrderTime());
            }

        }

        return patientInit;
    }

    /**
     * 查询患者信息表
     *
     * @param patientId
     * @return
     */
    @Override
    public TPatientInfo selectTPatientInfo(Integer patientId) {
        return patientInfoMapper.selectByPrimaryKey(patientId);
    }

    /**
     * 保存调查问卷调查
     *
     * @param doctorPushRel
     * @return
     */
    @Override
    public Integer saveDoctorPush(TDoctorPushRel doctorPushRel) {

        Integer count = 0;

        Map<String, Object> params = new HashMap<>();
//        params.put("bookingId",doctorPushRel.getBookingId());
        params.put("patientId", doctorPushRel.getPatientId());
        Map<String, Object> initMap = patientInitMapper.selectByMap(params);

        TPatientInit init = new TPatientInit();
        init.setRelId(Integer.parseInt(initMap.get("relId").toString()));
        init.setTherapyStatus(5);
        count += patientInitMapper.updateByPrimaryKeySelective(init);

        count += doctorPushRelMapper.insertSelective(doctorPushRel);
        Date now = new Date();
        String startDate = DateUtils.format(now, "yyyy-MM-dd");
        String endDate = DateUtils.addDay(now, 10);
        System.out.println("startDate = " + startDate + " endDate: " + endDate);

        // GET,POST参数全部支持，php无法接收Post参数，待优化
        String str = HttpUtils.sendPost("http://wechat.xrtn.dmpp.net.cn/children/frontend/web/index.php?r=wechat/sendtemplet&user_id=" +
                        doctorPushRel.getUserId() + "&booking_d=" + doctorPushRel.getBookingId() + "&doctor_id=" + doctorPushRel.getDoctorId() +
                        "&patient_id=" + doctorPushRel.getPatientId() + "&rel_id=" + doctorPushRel.getRelId() + "&startDate=" + startDate + "&endDate=" + endDate
                ,
                "&user_id=" + doctorPushRel.getUserId() +
                        "&booking_id=" + doctorPushRel.getBookingId() + "&doctor_id=" + doctorPushRel.getDoctorId() + "&patient_id=" + doctorPushRel.getPatientId() +
                        "&rel_id=" + doctorPushRel.getRelId() + "&startDate=" + startDate + "&endDate=" + endDate);
        System.out.println("str = " + str);

        return count;
    }

    public static void main(String args[]) {
//        String url = "http://wechat.xrtn.dmpp.net.cn/children/frontend/web/index.php?r=wechat/sendbookingsuccess";
//        //String params = "openId=o5u9Y1KjKj_E1mxgewii3LZ6Y_c0";
//        Map<String,String> params = new HashMap<>();
//        params.put("openId", "o5u9Y1HTRyUwPRH1l3jShZaK9IEY");
//
//        String str = HttpUtils.submitPostData(url, params,"utf-8");
//
//        System.out.println("params = "+params+"----------str=" + str);
//        long nowTime = System.currentTimeMillis()/1000;
//        Integer nowTimeInt = new Long(nowTime).intValue();
//        System.out.println(nowTimeInt);
//        System.out.println(0 == 0?"调理身体":"预防保健");

        TDoctorPushRel push = new TDoctorPushRel();
        push.setUserId(752);
        push.setDoctorId(1);
        new CommonServiceImpl().saveDoctorPush(new TDoctorPushRel());
    }

    /**
     * 根据患者id获取患者历史病历
     *
     * @param patientId
     * @return
     */
    @Override
    public TPatientHistory selectPatientHistoryByPatientId(Integer patientId) {
        return patientHistoryMapper.selectByPatientId(patientId);
    }

    /**
     * 根据患者id获取患者历史病历
     *
     * @param patientId
     * @return
     */
    @Override
    public List<Map<String, Object>> selectPatientTreatmentList(Integer patientId) {
        return patientTreatmentMapper.selectHistoryTreatmentList(patientId);
    }

    /**
     * 根据患者id获取患者历史病历
     *
     * @return
     */
    @Override
    public TPatientTreatment selectPatientTreatmentInfo(Map<String, Object> params) {
        return patientTreatmentMapper.selectByMap(params);
    }

    /**
     * 根据患者id修改患者历史病历
     *
     * @param record
     * @return
     */
    @Override
    public int updatePatientHistorySelective(TPatientHistory record) {
        record.setCreateTime(new Date());
        return patientHistoryMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public Map<String, Object> selectPatientInitMap(Map<String, Object> params) {
        return patientInitMapper.selectByMap(params);
    }

    /**
     * 新增患者历史病历
     *
     * @param record
     * @return
     */
    @Override
    public int insertPatientHistorySelective(TPatientHistory record) {

        Map<String, Object> params = new HashMap<>();
        //params.put("bookingId", record.getBookingId());
        params.put("patientId", record.getUserId());
        Map<String, Object> init = patientInitMapper.selectByMap(params);
        if (ObjUtils.isNotEmpty(init)) {
            TPatientInit patientInit = new TPatientInit();
            patientInit.setRelId(Integer.parseInt(init.get("relId").toString()));
            patientInit.setTherapyStatus(2);
            patientInitMapper.updateByPrimaryKeySelective(patientInit);
        }
        record.setCreateTime(new Date());
        if (null == patientHistoryMapper.selectByPatientId(record.getUserId())) {
            return patientHistoryMapper.insertSelective(record);
        } else {
            return -999;
        }
    }

    /**
     * 获取患者就诊记录
     *
     * @return
     */
    @Override
    public List<Map<String, Object>> selectPatientList(Map<String, Object> params) {

        List<Map<String, Object>> orderList = orderInfoMapper.selectPatientList(params);

        if (orderList.size() > 0) {
            for (Map<String, Object> order : orderList) {
                if (ObjUtils.isNotEmpty(order.get("treatmentId"))) {
                    List<BigDecimal> treatmentRatio = userTreatmentRelMapper.selectTreatmentRatioList(Integer.parseInt(order.get("treatmentId").toString()));
                    if (treatmentRatio.size() > 1) {
                        order.put("treatmentList", treatmentRatio.get(1));
                    } else {
                        order.put("treatmentList", null);
                    }
                }
            }
        }
        return orderList;
    }

    /**
     * 查询家庭护理表
     *
     * @return
     */
    @Override
    public List<TUserNersingRel> selectHomeNursingList(Integer patientId) {

        Map<String, Object> params = new HashMap<>();
        params.put("patientId", patientId);

        List<TUserNersingRel> nuringList = nersingRelMapper.selectByMap(params);

        return nuringList;
    }


    /**
     * 查询症状列表
     *
     * @return
     */
    @Override
    public List<InitDiseaseType> selectDiseaseTypeList() {
        return diseaseTypeMapper.selectDiseaseTypeList();
    }

    /**
     * 根据类型查询症状程度列表
     *
     * @param typeId
     * @return
     */
    @Override
    public List<InitDiseaseInfo> selectDiseaseInfoList(Integer typeId) {

        return diseaseInfoMapper.selectDiseaseInfoList(typeId);
    }

    /**
     * 穴位分组list
     *
     * @return
     */
    @Override
    public List<Map<String, Object>> selectPointGroupList() {

        List<InitPointType> typeList = pointTypeMapper.selectAll();

        List<InitPointInfo> infoList = pointInfoMapper.selectAll();

        List<Map<String, Object>> retMap = new ArrayList<>();

        for (InitPointType type : typeList) {
            Map<String, Object> typeMap = new HashMap<>();
            typeMap.put("typeName", type.getTypeName());
            typeMap.put("typeId", type.getTypeId());
            List<InitPointInfo> list = new ArrayList<>();
            for (InitPointInfo info : infoList) {
                if (type.getTypeId() == info.getTypeId()) {
                    list.add(info);
                }
            }
            typeMap.put("childList", list);
            retMap.add(typeMap);
        }

        return retMap;
    }

    /**
     * 查询推拿服务列表
     *
     * @return
     */
    @Override
    public List<InitServiceInfo> selectInitServiceList(Integer userId, Integer state, String serviceName) {

        return initServiceInfoMapper.selectAll(userId, state, serviceName);
    }

    /**
     * 查询药品列表
     *
     * @return
     */
    @Override
    public List<InitGoodsInfo> selectInitGoodsList(Integer state, String goodsName) {

        return initGoodsInfoMapper.selectAll(state, goodsName);
    }

    /**
     * 保存技师请假
     *
     * @param offInfo
     * @return
     */
    @Override
    public Integer saveDoctorOff(TOffInfo offInfo) {
        return offInfoMapper.insertSelective(offInfo);
    }

    /**
     * 撤销技师请假
     *
     * @param offInfo
     * @return
     */
    @Override
    public Integer deleteDoctorOff(TOffInfo offInfo) {
        Map<String, Object> params = new TreeMap<>();
        params.put("doctorId", offInfo.getUserId());
        params.put("bookingTime", offInfo.getOffDay());
        TOffInfo resOff = offInfoMapper.selectDoctorOff(params);
        return offInfoMapper.deleteByPrimaryKey(resOff.getOffId());
    }

    /**
     * 获取门店列表
     *
     * @param params
     * @return
     */
    @Override
    public List<TSubclinicInfo> selectSubclinicList(Map<String, Object> params) {
        return subclinicInfoMapper.selectByMap(params);
    }

    /**
     * 获取技师列表
     *
     * @param params
     * @return
     */
    @Override
    public List<SysUserInfo> selectSysUserList(Map<String, Object> params) {
        return sysUserInfoMapper.selectUserListByMap(params);
    }

    /**
     * 获取用户最大number
     *
     * @return
     */
    @Override
    public Integer selectUserMaxNo() {
        return sysUserInfoMapper.selectUserMaxNo();
    }

    /**
     * 获取技师列表
     *
     * @param params
     * @return
     */
    @Override
    public List<TUserInfo> selectUserList(Map<String, Object> params) {
        return userInfoMapper.selectByMap(params);
    }

    /**
     * 获取用户优惠券列表
     *
     * @param params
     * @return
     */
    @Override
    public List<Map<String, Object>> selectUserDiscountList(Map<String, Object> params) {
        params.put("isUsed", 0);

        Object serviceId = params.get("serviceId");
        List<Map<String, Object>> couponList = new ArrayList<>();
        if (ObjUtils.isNotEmpty(serviceId)) {

            String[] serviceIds = serviceId.toString().split(",");
            if (serviceIds.length > 1) {
                for (String sId : serviceIds) {
                    params.put("serviceId", sId);
                    couponList.addAll(couponUsrRelMapper.selectByMap(params));
                }
                List<Map<String, Object>> newList = new ArrayList(new HashSet(couponList));
                return newList;
            } else {
                couponList = couponUsrRelMapper.selectByMap(params);
                return couponList;
            }

        } else {
            couponList = couponUsrRelMapper.selectByMap(params);
            return couponList;
        }
    }

    /**
     * 新增预约
     *
     * @param bookingInfo
     * @return
     */
    @Override
    public TBookingInfo saveBookingInfo(TBookingInfo bookingInfo, TPatientInfo patientInfo) {
        //判断是否修改
        Map<String, Object> params = new HashMap<>();
        params.put("doctorId", bookingInfo.getDoctorId());
        if (ObjUtils.isNotEmpty(bookingInfo.getBookingTime())) {
            params.put("bookingTime", DateUtils.format(bookingInfo.getBookingTime(), DateUtils.YYYY_MM_DD));
        } else {
            params.put("bookingTime", DateUtils.format(new Date(), DateUtils.YYYY_MM_DD));
        }
        //判断是否预约
        TOffInfo offInfo = offInfoMapper.selectDoctorOff(params);
        if (ObjUtils.isNotEmpty(offInfo)) {
            return null;
        }

        SysUserInfo sysUserInfo = sysUserInfoMapper.selectByPrimaryKey(bookingInfo.getDoctorId());

        if (sysUserInfo.getIsWork() == 0) {
            return null;
        }

        String userName = bookingInfo.getUserName();
        if (ObjUtils.isEmpty(userName)) {
            userName = patientInfo.getPatientName();
            bookingInfo.setUserName(userName);
        }

        params.put("userPhone", bookingInfo.getUserPhone());
        List<TUserInfo> userInfoList = userInfoMapper.selectByMap(params);
        TUserInfo userInfo = new TUserInfo();

        if (userInfoList.size() == 0) { // 预约时如果手机号未存在系统用户表中，则创建用户
            userInfo.setUserName(userName);
            userInfo.setUserPhone(bookingInfo.getUserPhone());
            userInfo.setSubclinicId(bookingInfo.getSubclinicId());
            userInfo.setUserGender(bookingInfo.getUserGender());
            userInfoMapper.insertSelective(userInfo);
            bookingInfo.setUserId(userInfo.getUserId());
        } else {
            Integer subclinicId = userInfoList.get(0).getSubclinicId();
            if (ObjUtils.isEmpty(subclinicId)) { // 获客门店为空时，设置第一次下单的门店为获客门店
                userInfo.setSubclinicId(bookingInfo.getSubclinicId());
                userInfoMapper.updateByPrimaryKeySelective(userInfo);
            }
            userInfo.setUserPhone(userInfoList.get(0).getUserPhone());
            userInfo.setUserName(userInfoList.get(0).getUserName());
            userInfo.setOpenId(userInfoList.get(0).getOpenId());
            bookingInfo.setUserId(userInfoList.get(0).getUserId());
        }

        params.put("userId", bookingInfo.getUserId());

        dealPatientInfoAndInit(bookingInfo, patientInfo);

        bookingInfo.setBookingNo(ObjUtils.getOrderNo());
        bookingInfoMapper.insertSelective(bookingInfo);

        if (ObjUtils.isNotEmpty(bookingInfo.getBookingType())) {

            insertTreatment(bookingInfo);
            if (bookingInfo.getBookingType() == 0) {// 调理身体
                if (bookingInfo.getIsAdd() == 1) { // 新病程
                    newDegree(bookingInfo);
                } else {
                    dealTreatmentDegree(params, bookingInfo);
                }
            }
        }

        if (ObjUtils.isNotEmpty(sysUserInfo) && ObjUtils.isNotEmpty(userInfo)) {
            sendMessageAndPushWhenBookingSuccess(bookingInfo, sysUserInfo, userInfo);
        } else {
            System.out.println("----------未发送短信及微信推送！！！！sysUserInfo: " + sysUserInfo + "  userInfo: " + userInfo);
        }

        return bookingInfo;
    }

    private TPatientTreatment insertTreatment(TBookingInfo bookingInfo) {
        TPatientTreatment patientTreatment = new TPatientTreatment();
        patientTreatment.setUserId(bookingInfo.getUserId());
        patientTreatment.setPatientId(bookingInfo.getPatientId());
        if (bookingInfo.getBookingType() == 1) {
            patientTreatment.setDiseaseInfo("预防保健");
        } else {
            patientTreatment.setDiseaseInfo("调理身体");
        }
        patientTreatment.setBookingType(bookingInfo.getBookingType());
        patientTreatment.setIsAdd(bookingInfo.getIsAdd());
        patientTreatment.setBookingId(bookingInfo.getBookingId());
        //预防保健没有病程
        Map<String, Object> map = new HashMap<>();
        map.put("bookingId", bookingInfo.getBookingId());
        map.put("patientId", bookingInfo.getPatientId());
        if (null == patientTreatmentMapper.selectByBookingIdAndPatientId(map)) {
            patientTreatmentMapper.insertSelective(patientTreatment);
        }
        patientTreatment.setTreatmentId(patientTreatment.getTreatmentId());
        return patientTreatment;
    }

    private void newDegree(TBookingInfo bookingInfo) {
        //开启新病程
        TDegreeInfo degreeInfo = new TDegreeInfo();
        degreeInfo.setDegreeNo(ObjUtils.getDegreeNo());
        degreeInfo.setPatientId(bookingInfo.getPatientId());
        degreeInfo.setDoctorId(bookingInfo.getDoctorId());
        degreeInfo.setUserId(bookingInfo.getUserId());
        degreeInfo.setLastSubclinic(bookingInfo.getSubclinicId());
        degreeInfo.setLastTime(new Date());
        degreeInfoMapper.insertSelective(degreeInfo);
        //修改病程id
        TBookingInfo bookingInfos = bookingInfoMapper.selectByPrimaryKey(bookingInfo.getBookingId());
        if (ObjUtils.isNotEmpty(bookingInfos)) {
            bookingInfos.setDegreeId(degreeInfo.getDegreeId());
            bookingInfoMapper.updateByPrimaryKeySelective(bookingInfos);
            bookingInfo.setDegreeId(degreeInfo.getDegreeId());
        }
    }

    private void dealTreatmentDegree(Map<String, Object> params, TBookingInfo bookingInfo) {
        //查询上次病程id
        params.put("patientId", bookingInfo.getPatientId());
        params.put("degreeId", "1");
        params.put("old", "1");
        TPatientTreatment treatment = patientTreatmentMapper.selectByMap(params);
        if (ObjUtils.isNotEmpty(treatment)) {
            TBookingInfo bookings = bookingInfoMapper.selectByPrimaryKey(bookingInfo.getBookingId());
            if (ObjUtils.isNotEmpty(bookings)) {
                bookings.setDegreeId(treatment.getDegreeId());
                bookingInfoMapper.updateByPrimaryKeySelective(bookings);
            }
        } else {
            //开启新病程
            TDegreeInfo degreeInfo = new TDegreeInfo();
            degreeInfo.setDegreeNo(ObjUtils.getDegreeNo());
            degreeInfo.setPatientId(bookingInfo.getPatientId());
            degreeInfo.setDoctorId(bookingInfo.getDoctorId());
            degreeInfo.setUserId(bookingInfo.getUserId());
            degreeInfo.setLastSubclinic(bookingInfo.getSubclinicId());
            degreeInfo.setLastTime(new Date());
            degreeInfoMapper.insertSelective(degreeInfo);
            //修改病程ids
            TBookingInfo bookings = bookingInfoMapper.selectByPrimaryKey(bookingInfo.getBookingId());
            if (ObjUtils.isNotEmpty(bookings)) {
                bookings.setDegreeId(degreeInfo.getDegreeId());
                bookingInfoMapper.updateByPrimaryKeySelective(bookings);
            }
        }
    }

    private void dealPatientInfoAndInit(TBookingInfo bookingInfo, TPatientInfo patientInfoSrc) {
        if (ObjUtils.isEmpty(bookingInfo.getPatientId())) {
            TPatientInfo patientInfo = new TPatientInfo();
            try {
                if (ObjUtils.isNotEmpty(patientInfoSrc.getPatientBirthday())) {
                    patientInfo.setPatientAge(DateUtils.getCurrentAgeByBirthdate(patientInfoSrc.getPatientBirthday()));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            patientInfo.setPatientName(patientInfoSrc.getPatientName());
            patientInfo.setUserId(bookingInfo.getUserId());
            patientInfo.setPatientGender(patientInfoSrc.getPatientGender());
            patientInfo.setPatientBirthday(patientInfoSrc.getPatientBirthday());
            patientInfo.setPatientHeight(patientInfoSrc.getPatientHeight());
            patientInfo.setPatientBodyWeight(patientInfoSrc.getPatientBodyWeight());
            patientInfoMapper.insertSelective(patientInfo);

            bookingInfo.setPatientId(patientInfo.getPatientId());

            TPatientInit init = new TPatientInit();
            init.setUserName(patientInfoSrc.getPatientName());
            init.setUserAge(patientInfo.getPatientAge());
            init.setUserGender(patientInfoSrc.getPatientGender());
            init.setUserBirthday(patientInfoSrc.getPatientBirthday());
            init.setPatientId(patientInfo.getPatientId());
            init.setBookingId(bookingInfo.getBookingId());
            init.setUserBodyWeight(patientInfoSrc.getPatientBodyWeight());
            init.setUserHeight(patientInfoSrc.getPatientHeight());
            patientInitMapper.insertSelective(init);
        }
    }

    private void sendMessageAndPushWhenBookingSuccess(TBookingInfo bookingInfo, SysUserInfo sysUserInfo, TUserInfo userInfo) {
        TSubclinicInfo subclinicInfo = subclinicInfoMapper.selectByPrimaryKey(bookingInfo.getSubclinicId());
        TPatientInfo patientInfo = patientInfoMapper.selectByPrimaryKey(bookingInfo.getPatientId());
        //正式
        //发给预约人短信提醒
//        SendValidataCode.restAPI.sendTemplateSMS(userInfo.getUserPhone(), "328291",
//                new String[]{subclinicInfo.getSubclinicName(), sysUserInfo.getUserName(),
//                        DateUtils.format(bookingInfo.getBookingTime(),DateUtils.YYYY_MM_DD_HH_MM_SS)});
//        SendValidataCode.sendBookingOk(userInfo.getUserPhone(),subclinicInfo.getSubclinicName(),
//                bookingInfo.getBookingType() == 0?"调理身体":"预防保健",
//                sysUserInfo.getUserName(),
//                DateUtils.format(bookingInfo.getBookingTime(),DateUtils.YYYY_MM_DD_HH_MM_SS),"254566");
//        //发给技师短信提醒
        SendValidataCode.sendBookingOk(sysUserInfo.getUserPhone(), patientInfo.getPatientName(),
                DateUtils.format(bookingInfo.getBookingTime(), DateUtils.YYYY_MM_DD_HH_MM_SS), "247426");

        //推送微信

        String url = "http://wechat.xrtn.dmpp.net.cn/children/frontend/web/index.php?r=wechat/sendbookingsuccess";
        Map<String, String> param = new HashMap<>();
        param.put("openId", userInfo.getOpenId());
        param.put("patientName", patientInfo.getPatientName());
        param.put("bookingTime", DateUtils.format(bookingInfo.getBookingTime(), DateUtils.YYYY_MM_DD_HH_MM_SS));
        param.put("subclinicName", subclinicInfo.getSubclinicName());
        param.put("doctorName", sysUserInfo.getUserName());

        //String param = "openId="+userInfo.getOpenId()+"&patientName="+patientInfo.getPatientName()+"&bookingTime="+DateUtils.format(bookingInfo.getBookingTime(),DateUtils.YYYY_MM_DD_HH_MM_SS)+"&subclinicName="+subclinicInfo.getSubclinicName()+"&doctorName="+sysUserInfo.getUserName();

        String strs = HttpUtils.submitPostData(url, param, "utf-8");

        System.out.println("params = " + param.toString() + "----------strs=" + strs);
    }

    /**
     * 新增预约
     *
     * @param bookingInfo
     * @return
     */
    @Override
    public Map<String, Object> saveBookingInfo(TBookingInfo bookingInfo) {

        Map<String, Object> params = new HashMap<>();
        params.put("doctorId", bookingInfo.getDoctorId());
        if (ObjUtils.isNotEmpty(bookingInfo.getBookingTime())) {
            params.put("bookingTime", DateUtils.format(bookingInfo.getBookingTime(), DateUtils.YYYY_MM_DD));
        } else {
            params.put("bookingTime", DateUtils.format(new Date(), DateUtils.YYYY_MM_DD));
            bookingInfo.setBookingTime(new Date());
        }
        //判断是否可预约
        TOffInfo offInfo = offInfoMapper.selectDoctorOff(params);
        if (ObjUtils.isNotEmpty(offInfo)) {
            return null;
        }
        SysUserInfo sysUserInfo = sysUserInfoMapper.selectByPrimaryKey(bookingInfo.getDoctorId());

        if (sysUserInfo.getIsWork() == 0) {
            return null;
        }
        TUserInfo userInfo = new TUserInfo();
        if (ObjUtils.isNotEmpty(bookingInfo.getUserId())) {
            userInfo = userInfoMapper.selectByPrimaryKey(bookingInfo.getUserId());
            bookingInfo.setUserPhone(userInfo.getUserPhone());
            bookingInfo.setUserName(userInfo.getUserName());
        }

        bookingInfo.setBookingNo(ObjUtils.getOrderNo());
        bookingInfoMapper.insertSelective(bookingInfo);
        //查询上一次就诊的病程id
        TPatientTreatment patientTreatment = new TPatientTreatment();
        if (ObjUtils.isNotEmpty(bookingInfo.getBookingType())) {

            patientTreatment = insertTreatment(bookingInfo);
            bookingInfo.setTreatmentId(patientTreatment.getTreatmentId());

            if (bookingInfo.getBookingType() == 0) { //调理身体
                if (bookingInfo.getIsAdd() == 1) { // 开启新病程
                    newDegree(bookingInfo);
                } else {
                    dealTreatmentDegree(params, bookingInfo);
                }
            }
        }

        sendMessageAndPushWhenBookingSuccess(bookingInfo, sysUserInfo, userInfo);

        Map<String, Object> retMap = new HashMap<>();
        retMap.put("bookingId", bookingInfo.getBookingId());
        retMap.put("treatmentId", patientTreatment.getTreatmentId());
        return retMap;
    }

    private TBookingInfo updateBookingUpdateDegreeInfo(TBookingInfo bookingInfo) {
        TDegreeInfo degreeInfo = new TDegreeInfo();
        degreeInfo.setDegreeNo(ObjUtils.getDegreeNo());
        degreeInfo.setPatientId(bookingInfo.getPatientId());
        degreeInfo.setUserId(bookingInfo.getUserId());
        degreeInfo.setDoctorId(bookingInfo.getDoctorId());
        degreeInfo.setCreateTime(new Date());
        degreeInfo.setLastSubclinic(bookingInfo.getSubclinicId());
        degreeInfo.setLastTime(new Date());
        degreeInfoMapper.insertSelective(degreeInfo);
        bookingInfo.setDegreeId(degreeInfo.getDegreeId());
        return bookingInfo;
    }

    /**
     * 修改预约
     *
     * @param bookingInfo
     * @return
     */
    @Override
    public Map<String, Object> updateBooking(TBookingInfo bookingInfo) {

        if (ObjUtils.isNotEmpty(bookingInfo.getBookingType())) {
            if (bookingInfo.getIsAdd() == 0) {
                //继续治疗
                //根据患者id查询上次病程id
                TDegreeInfo degreeInfo = degreeInfoMapper.selectByPatientId(bookingInfo.getPatientId());
                if (ObjUtils.isNotEmpty(degreeInfo)) {
                    bookingInfo.setDegreeId(degreeInfo.getDegreeId());
                } else {
                    bookingInfo = updateBookingUpdateDegreeInfo(bookingInfo);
                }
            } else {
                //新病程
                TDegreeInfo degreeInfo = degreeInfoMapper.selectByPatientId(bookingInfo.getPatientId());
                if (ObjUtils.isEmpty(degreeInfo)) {
                    bookingInfo = updateBookingUpdateDegreeInfo(bookingInfo);
                }

            }
        }

        if (ObjUtils.isNotEmpty(bookingInfo.getBookingId())) {

            Map<String, Object> params = new HashMap<>();
            params.put("bookingId", bookingInfo.getBookingId());

            TPatientTreatment treatment = patientTreatmentMapper.selectByMap(params);

            if (ObjUtils.isNotEmpty(treatment)) {

                treatment.setBookingType(bookingInfo.getBookingType());
                treatment.setIsAdd(bookingInfo.getIsAdd());
                treatment.setPatientId(bookingInfo.getPatientId());
                patientTreatmentMapper.updateByPrimaryKeySelective(treatment);

            } else {
                insertTreatment(bookingInfo);
            }
        }

        bookingInfoMapper.updateByPrimaryKeySelective(bookingInfo);

        Map<String, Object> retMap = new HashMap<>();
        retMap.put("bookingId", bookingInfo.getBookingId());
        retMap.put("treatmentId", null);

        return retMap;
    }

    /**
     * 新增预约
     *
     * @param bookingTime
     * @param subclinicId
     * @return
     */
    @Override
    public List<Map<String, Object>> selectFreeDoctor(String bookingTime, Integer subclinicId) {

        Map<String, Object> retMap = new HashMap<>();
        retMap.put("bookingDate", bookingTime);
        retMap.put("subclinicId", subclinicId);
        retMap.put("isWork", 1);

        return bookingInfoMapper.selectFreeDoctor(retMap);
    }

    /**
     * 后台 ： 查询预约列表
     *
     * @param params
     * @return
     */
    @Override
    public List<Map<String, Object>> selectBookingList(Map<String, Object> params) {

        Object patientId = params.get("patientId");

        if (ObjUtils.isNotEmpty(patientId)) {
            return bookingInfoMapper.selectBookingListByPatientId(params);
        } else {

            List<Map<String, Object>> list = new ArrayList<>();

            try {
                String str = DateUtils.format(new Date(), DateUtils.YYYY_MM_DD);
                Date date = DateUtils.parse(str, DateUtils.YYYY_MM_DD);
                Calendar dq = Calendar.getInstance();
                dq.setTime(date);

                list = bookingInfoMapper.selectBookingList(params);
                if (list.size() > 0) {
                    for (Map<String, Object> map : list) {
                        if (ObjUtils.isNotEmpty(map.get("patientBirthday"))) {
                            String dd = map.get("patientBirthday").toString();
                            Date date2 = DateUtils.parse(dd, DateUtils.YYYY_MM_DD);
                            Calendar rz = Calendar.getInstance();
                            rz.setTime(date2);
                            map.put("patientBirthday", DateUtils.getDate(dq, rz));
                        }

                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

            return list;
        }


    }

    /**
     * 后台 ： 查询预约列表 - 分页
     *
     * @param page
     * @param params
     * @return
     */
    @Override
    public Page selectBookingPageList(Page page, Map<String, Object> params) {
        Object patientId = params.get("patientId");
        if (ObjUtils.isNotEmpty(patientId)) {
            page.setItems(bookingInfoMapper.selectBookingPageListByPatientId(page, params));
            return page;
        } else {

            List<Map<String, String>> list = bookingInfoMapper.selectBookingPageList(page, params);
            if (list.size() > 0) {
                for (Map<String, String> map : list) {
                    try {
                        if (ObjUtils.isNotEmpty(map.get("patientBirthday"))) {
                            String str = DateUtils.format(new Date(), DateUtils.YYYY_MM_DD);
                            Date date = DateUtils.parse(str, DateUtils.YYYY_MM_DD);
                            Calendar dq = Calendar.getInstance();
                            dq.setTime(date);
                            String dd = map.get("patientBirthday").toString();
                            Date date2 = DateUtils.parse(dd, DateUtils.YYYY_MM_DD);
                            Calendar rz = Calendar.getInstance();
                            rz.setTime(date2);
                            map.put("patientBirthday", DateUtils.getDate(dq, rz));
                        }
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }

                }
            }
            Collections.sort(list, new Comparator<Map<String, String>>() {
                public int compare(Map<String, String> o1, Map<String, String> o2) {
                    return o2.get("bookingTime").compareTo(o1.get("bookingTime"));
                }
            });


            page.setItems(list);

            return page;
        }
    }

    /**
     * 查询预约看板按周分组
     *
     * @param params
     * @return
     */
    @Override
    public Map<String, Object> selectBookingWeekList(Map<String, Object> params) {

        Map<String, Object> retMap = new HashMap<>();

        //params.put("bookingStatus", 0);
        List<Map<String, Object>> bookList = bookingInfoMapper.selectBookingWeekList(params);

        List<String> dayList = DateUtils.getMonthDateList(params.get("startDate").toString());

        List<Map<String, Object>> weekList = new ArrayList<>();
        for (Map<String, Object> bookMap : bookList) {
            weekList.add(bookMap);
        }
        List<Map<String, Object>> newList = new ArrayList(new HashSet(weekList));
        List<Map<String, Object>> retList = new ArrayList();
        for (String day : dayList) {
            Map<String, Object> typeMap = new HashMap<>();
            List<Map<String, Object>> list = new ArrayList<>();
            Integer amCount = 0, pmCount = 0;
            Object today = null;
            for (Map<String, Object> bookMap : bookList) {
                String days = bookMap.get("days").toString();

                if (day.equals(days)) {
                    today = bookMap.get("today");
                    Integer hours = Integer.parseInt(bookMap.get("hours").toString());
                    if (hours < 13) {
                        amCount++;
                    } else {
                        pmCount++;
                    }
                    list.add(bookMap);
                }
            }
            typeMap.put("amCount", amCount);
            typeMap.put("pmCount", pmCount);
            typeMap.put("childList", list);
            try {
                typeMap.put("weekNum", DateUtils.getWeekOfDate(DateUtils.parse(day, DateUtils.YYYY_MM_DD)));
                typeMap.put("today", day.substring(5, day.length()).replace("-", ""));
            } catch (Exception e) {
            }
            retList.add(typeMap);
        }
        Integer subclinicId = Integer.parseInt(params.get("subclinicId").toString());
        if (subclinicId == 0) {
            subclinicId = 1;
        }

        retMap.put("bookingList", retList);

        TSubclinicInfo subclinicInfo = subclinicInfoMapper.selectMaxEntTime(params);
        retMap.put("subclinicInfo", subclinicInfo);

        return retMap;
    }

    /**
     * 查询预约看板按周分组
     *
     * @param params
     * @return
     */
    @Override
    public Map<String, Object> selectBookingStatInfo(Map<String, Object> params) {

        Map<String, Object> retMap = new HashMap<>();

        List<Map<String, Object>> bookList = bookingInfoMapper.selectBookingWeekList(params);


        List<Map<String, Object>> retList = new ArrayList();
        for (Integer day = 1; day <= 7; day++) {
            Map<String, Object> typeMap = new HashMap<>();
            List<Map<String, Object>> list = new ArrayList<>();
            Integer amCount = 0, pmCount = 0;
            for (Map<String, Object> bookMap : bookList) {
                Integer weekDay = (Integer) bookMap.get("weekDay");
                if (weekDay == day) {
                    Integer hours = Integer.parseInt(bookMap.get("hours").toString());
                    if (hours < 13) {
                        amCount++;
                    } else {
                        pmCount++;
                    }
                    list.add(bookMap);
                }
            }
            typeMap.put("amCount", amCount);
            typeMap.put("pmCount", pmCount);
            typeMap.put("childList", list);
            typeMap.put("weekNum", DateUtils.getWeekOfIntegerDay(day));

            retList.add(typeMap);
        }

        retMap.put("bookingList", retList);

        TSubclinicInfo subclinicInfo = subclinicInfoMapper.selectMaxEntTime(params);
        retMap.put("subclinicInfo", subclinicInfo);

        return retMap;
    }

    /**
     * 后台 ： 查询预约列表
     *
     * @param bookingId
     * @return
     */
    @Override
    public TBookingInfo selectBookingByPrimaryKey(Integer bookingId) {
        return bookingInfoMapper.selectByPrimaryKey(bookingId);
    }

    /**
     * 后台 ： 查询预约列表
     *
     * @param params
     * @return
     */
    @Override
    public Map<String, Object> selectBookingBoardList(Map<String, Object> params) {

        params.put("notCancel", 1); // 过滤掉已无效
        List<TBookingInfo> bookingList = bookingInfoMapper.selectBookingLists(params);

        Map<String, Object> retMap = new HashMap<>();

        List<Map<String, Object>> doctorList = new ArrayList<>();
        for (TBookingInfo bookingInfo : bookingList) {
            Map<String, Object> map = new HashMap<>();
            map.put("doctorName", bookingInfo.getDoctorName());
            map.put("offDay", bookingInfo.getOffDay());
            map.put("doctorId", bookingInfo.getDoctorId());
            map.put("subclinicId", bookingInfo.getSubclinicId());
            map.put("subclinicName", bookingInfo.getSubclinicName());
            map.put("isWork", bookingInfo.getDoctorIsWork());
            map.put("doctorWorkStartTime", bookingInfo.getDoctorWorkStartTime());
            map.put("doctorWorkEndTime", bookingInfo.getDoctorWorkEndTime());
            doctorList.add(map);
        }
        List<Map<String, Object>> newList = new ArrayList(new HashSet(doctorList));

        List<Map<String, Object>> bookingListMap = new ArrayList<>();

        for (Map<String, Object> map : newList) {
            Map<String, Object> typeMap = new HashMap<>();
            typeMap.put("doctorName", map.get("doctorName"));
            typeMap.put("doctorId", map.get("doctorId"));
            typeMap.put("offDay", map.get("offDay"));
            typeMap.put("isWork", map.get("isWork"));
            typeMap.put("startTime", map.get("doctorWorkStartTime"));
            typeMap.put("endTime", map.get("doctorWorkEndTime"));
            if (map.get("offDay").toString().equals("0")) {
                List<TBookingInfo> list = new ArrayList<>();
                for (TBookingInfo info : bookingList) {
                    if (map.get("doctorName").toString().equals(info.getDoctorName()) && info.getBookingId() != null) {
                        list.add(info);
                    }
                }
                typeMap.put("subclinicId", map.get("subclinicId"));
                typeMap.put("subclinicName", map.get("subclinicName"));
                typeMap.put("childList", list);
            } else {
                typeMap.put("childList", null);
            }
            bookingListMap.add(typeMap);
        }

        Collections.sort(bookingListMap, new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                return Integer.parseInt(o1.get("doctorId").toString()) - Integer.parseInt(o2.get("doctorId").toString());
            }
        });

        retMap.put("bookingList", bookingListMap);

        TSubclinicInfo subclinicInfo = subclinicInfoMapper.selectMaxEntTime(params);
        retMap.put("subclinicInfo", subclinicInfo);

        return retMap;
    }

    /**
     * 后台 ： 查询商品消耗统计
     *
     * @param params
     * @return
     */
    @Override
    public List<Map<String, Object>> selectGoodsStatic(Map<String, Object> params) {
        return orderInfoMapper.selectGoodsStatic(params);
    }

    /**
     * 后台 ： 查询预约列表
     *
     * @return
     */
    @Override
    public SysUserInfo selectSysUserInfo(Map<String, Object> params) {
        return sysUserInfoMapper.selectByUserInfo(params);
    }

    /**
     * 后台 ： 查询储值卡||计次卡列表
     *
     * @param params
     * @return
     */
    @Override
    public List<SysAccountCardInfo> selectSysCardList(Map<String, Object> params) {

        List<SysAccountCardInfo> cardList = accountCardInfoMapper.selectByMap(params);

        return cardList;
    }

    /**
     * 后台 ： 查询储值卡||计次卡列表
     *
     * @param params
     * @return
     */
    @Override
    public List<SysDiscountCardInfo> selectSysDiscountCardList(Map<String, Object> params) {
        return discountCardInfoMapper.selectByMap(params);
    }

    /**
     * 后台 ： 查询用户计次卡列表
     *
     * @param params
     * @return
     */
    @Override
    public List<TCardUsrRel> selectUserCardList(Map<String, Object> params) {

        return cardUsrRelMapper.selectByListMap(params);
    }

    /**
     * 后台 ： 查询储值卡||计次卡详情
     *
     * @param cardId
     * @return
     */
    @Override
    public SysAccountCardInfo selectSysCardInfo(Integer cardId) {

        SysAccountCardInfo cardInfo = accountCardInfoMapper.selectByPrimaryKey(cardId);

        if (ObjUtils.isNotEmpty(cardInfo.getServiceId())) {

            InitServiceInfo serviceInfo = initServiceInfoMapper.selectByPrimaryKey(cardInfo.getServiceId());

            cardInfo.setServiceName(serviceInfo.getServiceName());
        } else {
            cardInfo.setServiceName("该服务已下架");
        }

        return cardInfo;
    }

    /**
     * 后台 ： 优惠券详情
     *
     * @param cardId
     * @return
     */
    @Override
    public SysDiscountCardInfo selectSysDiscountCardInfo(Integer cardId) {

        SysDiscountCardInfo cardInfo = discountCardInfoMapper.selectByPrimaryKey(cardId);

        if (ObjUtils.isNotEmpty(cardInfo)) {
            if (ObjUtils.isNotEmpty(cardInfo.getServiceId())) {

                InitServiceInfo serviceInfo = initServiceInfoMapper.selectByPrimaryKey(cardInfo.getServiceId());

                if (ObjUtils.isNotEmpty(serviceInfo)) {
                    cardInfo.setServiceName(serviceInfo.getServiceName());
                }
            }
        }
        return cardInfo;
    }

    /**
     * 后台 ： 新增储值卡||计次卡列表
     *
     * @param accountCardInfo
     * @return
     */
    @Override
    public Integer saveSysAccountCardInfo(SysAccountCardInfo accountCardInfo) {
        return accountCardInfoMapper.insertSelective(accountCardInfo);
    }

    /**
     * 后台 ： 修改储值卡||计次卡列表
     *
     * @param accountCardInfo
     * @return
     */
    @Override
    public Integer updateSysAccountCardInfo(SysAccountCardInfo accountCardInfo) {
        return accountCardInfoMapper.updateByPrimaryKeySelective(accountCardInfo);
    }

    /**
     * 后台 ： 新增优惠券
     *
     * @param discountCardInfo
     * @return
     */
    @Override
    public Integer saveSysDiscountCardInfo(SysDiscountCardInfo discountCardInfo, HttpServletRequest request) {

        if (discountCardInfo.getCardType() == 3) {
            discountCardInfo.setTargetCost(new BigDecimal(0));
            discountCardInfo.setDiscountCosts(discountCardInfo.getDiscountCost());
        }

        Integer reuslt = discountCardInfoMapper.insertSelective(discountCardInfo);

        // 添加shareUrl
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
        String fullUrl = basePath + "/card/couponShare?couponId=" + discountCardInfo.getCardId();

        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        OkHttpClient client = new OkHttpClient();

        FormBody.Builder bulder = new FormBody.Builder();
        bulder.add("real_url", fullUrl);
        bulder.add("domain", "hub9.cn");
        bulder.add("access_token", CommonConfig.dwz_access_token);

        RequestBody body = bulder.build();
        Request okReq = new Request.Builder()
                .url("https://dwz3.cn/apis/urls/add")
                .post(body)
                .build();

        String respStr = "";
        try {
            Response okResp = client.newCall(okReq).execute();
            respStr = okResp.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }


//        String str = HttpUtils.sendPost("https://dwz3.cn/apis/urls/add", "real_url=" + fullUrl + "&domain=hub9.cn&access_token=" + CommonConfig.dwz_access_token);
//        System.out.println(str);
        String dataStr = JSONObject.fromObject(respStr).optString("data");
        String shortUrl = "";
        if (!dataStr.equals("[]")) {
            shortUrl = JSONObject.fromObject(dataStr).optString("short_url");
        }
        discountCardInfo.setShareFullUrl(fullUrl);
        discountCardInfo.setShareShortUrl(shortUrl);

        discountCardInfoMapper.updateByPrimaryKeySelective(discountCardInfo);

        return reuslt;
    }

    /**
     * 后台 ： 修改优惠券
     *
     * @param discountCardInfo
     * @return
     */
    @Override
    public Integer updateSysDiscountCardInfo(SysDiscountCardInfo discountCardInfo) {

        if (ObjUtils.isNotEmpty(discountCardInfo.getCardType())) {
            if (discountCardInfo.getCardType() == 3) {
                discountCardInfo.setDiscountCosts(discountCardInfo.getDiscountCost());
            }
        }
        return discountCardInfoMapper.updateByPrimaryKeySelective(discountCardInfo);
    }

    /**
     * 后台 ： 删除优惠券
     *
     * @param cardId
     * @return
     */
    @Override
    public Integer deleteSysDiscountCardInfo(Integer cardId) {

        SysDiscountCardInfo cardInfo = selectSysDiscountCardInfo(cardId);
        if (ObjUtils.isNotEmpty(cardInfo)) {
            cardInfo.setIsDelete(1);
            return discountCardInfoMapper.updateByPrimaryKeySelective(cardInfo);
        }

        return 0;
    }

    /**
     * 后台 ： 删除优惠券
     *
     * @param cardId
     * @return
     */
    @Override
    public Integer deleteSysAccountCardInfo(Integer cardId) {
        SysAccountCardInfo cardInfo = accountCardInfoMapper.selectByPrimaryKey(cardId);

        if (ObjUtils.isNotEmpty(cardInfo)) {
            cardInfo.setIsDelete(1);
            return accountCardInfoMapper.updateByPrimaryKeySelective(cardInfo);
        }

        return 0;
    }

    /**
     * 用户开卡
     *
     * @param cardId
     * @param userId
     * @return
     */
    @Override
    public Integer saveUserCard(Integer cardId, Integer userId, Integer cardType, Integer doctorId, Integer subclinicId, Integer payWay, String cardDesc) {

        Integer count = 0;

        SysAccountCardInfo accountCardInfo = accountCardInfoMapper.selectByPrimaryKey(cardId);

        if (ObjUtils.isEmpty(accountCardInfo)) {
            return 0;
        }

        //校验收银人员是否有收银权限
        boolean isPay = false;
        if (ObjUtils.isNotEmpty(doctorId)) {
            SysUserInfo sysUserInfo = sysUserInfoMapper.selectByPrimaryKey(doctorId);
            List<Map<String, Object>> userFunctionList = roleInfoMapper.selectRoleLists(sysUserInfo.getUserRole());

            List<String> groupList = new ArrayList<>();

            for (Map<String, Object> functionMap : userFunctionList) {
                groupList.add(functionMap.get("menuName").toString());
                if (Integer.parseInt(functionMap.get("functionId").toString()) == 72) {
                    isPay = true;
                }
            }
            if (isPay == false) {
                return 0;
            }
        }


        AccountUserInfo accountUserInfo = new AccountUserInfo();


        //1满减，2体验券，3通用，4充值，5记次卡
        if (accountCardInfo.getCardType() == 4) {
            //生成账务流水
            //类型：0:余额;1:次卡;2:储值

            accountUserInfo.setCardType(2);
            accountUserInfo.setAccountDesc(accountCardInfo.getCardName());
            accountUserInfo.setBalancePayCost(accountCardInfo.getAccountDiscount());
            //修改余额
            TUserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
            if (ObjUtils.isEmpty(userInfo)) {
                return 0;
            }
            userInfo.setUserAccount(userInfo.getUserAccount().add(new BigDecimal(accountCardInfo.getCardValue())));
            Calendar c = Calendar.getInstance();
            if (userInfo.getOutTime().getTime() > new Date().getTime()) {
                c.setTime(userInfo.getOutTime());
            } else {
                c.setTime(new Date());
            }
            c.add(Calendar.DAY_OF_MONTH, accountCardInfo.getValidTime());
            userInfo.setOutTime(c.getTime());
            count += userInfoMapper.updateByPrimaryKeySelective(userInfo);
        }
        if (accountCardInfo.getCardType() == 5) {
            accountUserInfo.setAccountDesc(accountCardInfo.getCardName());
            //类型：0:余额;1:次卡;2:储值
            accountUserInfo.setCardType(1);
            //类型：0:消费;1:充值;2:其他
            accountUserInfo.setAccountType(2);
        } else {
            accountUserInfo.setAccountType(1);
        }

        //生成账务
        accountUserInfo.setCardId(String.valueOf(accountCardInfo.getCardId()));
        accountUserInfo.setAccountNo(ObjUtils.getAccountNo());
        accountUserInfo.setUserId(userId);
        accountUserInfo.setPayWay(payWay);
        accountUserInfo.setCashierId(doctorId);
        accountUserInfo.setSubclinicId(subclinicId);
        accountUserInfo.setAccountCost(accountCardInfo.getAccountDiscount());
        accountUserInfo.setCreateTime(new Date());

        count += accountUserInfoMapper.insertSelective(accountUserInfo);

        //开卡
        TCardUsrRel cardUsrRel = new TCardUsrRel();
        //次卡应该获取次卡对应的服务id
        cardUsrRel.setCardId(accountCardInfo.getCardId());
        cardUsrRel.setServiceId(accountCardInfo.getServiceId());
        cardUsrRel.setCardLeftTime(accountCardInfo.getCardCount());
        cardUsrRel.setCreateTime(new Date());
        cardUsrRel.setUserId(userId);
        cardUsrRel.setSubclinicId(subclinicId);
        cardUsrRel.setDoctorId(doctorId);
        cardUsrRel.setCardDesc(cardDesc);

        try {
            cardUsrRel.setInvalidTime(DateUtils.parse(DateUtils.addDay(new Date(), accountCardInfo.getValidTime()), DateUtils.YYYY_MM_DD));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        cardUsrRel.setDoctorId(doctorId);
        //开卡关系表，新增流水id
        cardUsrRel.setAccountId(accountUserInfo.getAccountId());
        count += cardUsrRelMapper.insertSelective(cardUsrRel);
        return count;
    }

    /**
     * 发放优惠券
     *
     * @param userCouponArray
     * @return
     */
    @Override
    public Integer saveUserCoupon(String userCouponArray) {
        Integer count = 0;
        JSONArray userCouponArrays = JSONArray.fromObject(userCouponArray);
        if (userCouponArrays.size() > 0) {

            Integer couponId = userCouponArrays.getJSONObject(0).optInt("couponId");

            Integer useCount = discountCardInfoMapper.selectCouponCount(couponId);
            SysDiscountCardInfo cardInfo = discountCardInfoMapper.selectByPrimaryKey(couponId);
            if (ObjUtils.isEmpty(cardInfo)) {
                return 0;
            }
            if ((useCount + userCouponArrays.size()) > cardInfo.getCardCount()) {
                return 0;
            }

            for (int i = 0; i < userCouponArrays.size(); i++) {
                JSONObject jsonObject = userCouponArrays.getJSONObject(i);
                TCouponUsrRel couponUsrRel = new TCouponUsrRel();
                couponUsrRel.setCardType(jsonObject.optInt("cardType"));
                couponUsrRel.setCreateTime(new Date());
                couponUsrRel.setCouponId(jsonObject.optInt("couponId"));
                couponUsrRel.setIsUsed(0);
                couponUsrRel.setUserId(jsonObject.optInt("userId"));
                try {
                    couponUsrRel.setUseTime(DateUtils.parse(DateUtils.addDay(new Date(), jsonObject.getInt("validDay")), DateUtils.YYYY_MM_DD));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                count += couponUsrRelMapper.insertSelective(couponUsrRel);
            }
        }

        return count;
    }

    /**
     * 发放优惠券
     *
     * @param couponUsrRel
     * @return
     */
    @Override
    public Integer saveUseCoupon(TCouponUsrRel couponUsrRel) {

        Integer count = 0;

        if (ObjUtils.isNotEmpty(couponUsrRel.getUserPhone()) && ObjUtils.isNotEmpty(couponUsrRel.getCouponId())) {
            Map<String, Object> params = new HashMap<>();
            params.put("userPhone", couponUsrRel.getUserPhone());
            List<TUserInfo> userInfoList = userInfoMapper.selectByMap(params);

            TUserInfo userInfo = new TUserInfo();

            if (userInfoList.size() > 0) {
                couponUsrRel.setUserId(userInfoList.get(0).getUserId());
            } else {
                userInfo.setUserPhone(couponUsrRel.getUserPhone());
                count += userInfoMapper.insertSelective(userInfo);

                couponUsrRel.setUserId(userInfo.getUserId());
            }

            count += couponUsrRelMapper.insertSelective(couponUsrRel);
        }

        return count;
    }

    /**
     * 发放优惠券
     *
     * @param couponId
     * @param userPhone
     * @return
     */
    @Override
    public ResponseData saveUseCoupon(Integer couponId, String userPhone, ResponseData data) {

        if (ObjUtils.isEmpty(userPhone) || userPhone.length() < 11) {
            data.setCodeEnum(CodeEnum.CODE_10004);
            return data;
        }
        SysDiscountCardInfo discountCardInfo = discountCardInfoMapper.selectByPrimaryKey(couponId);

        if (ObjUtils.isEmpty(discountCardInfo)) {
            data.setCodeEnum(CodeEnum.CODE_60015);
            return data;
        }
        if (discountCardInfo.getCardState() == 0) {
            data.setCodeEnum(CodeEnum.CODE_60015);
            return data;
        }

        if (ObjUtils.isNotEmpty(userPhone)) {
            Map<String, Object> params = new HashMap<>();
            params.put("userPhone", userPhone);
            List<TUserInfo> userList = userInfoMapper.selectByMap(params);

            params.put("couponId", couponId);
            //校验该优惠券是否超出领取数量
            List<TCouponUsrRel> couponList = couponUsrRelMapper.selectByCouponId(couponId);
            if (couponList.size() > discountCardInfo.getCardCount()) {
                data.setCodeEnum(CodeEnum.CODE_60012);
                return data;
            }
            Integer userId = 0;

            //根据手机号查询该用户，获取用户id
            if (userList.size() > 0) {
                params.put("userId", userList.get(0).getUserId());
                userId = userList.get(0).getUserId();
            } else {
                TUserInfo userInfo = new TUserInfo();
                userInfo.setUserPhone(userPhone);
                userInfo.setUserName(userPhone);
                userInfoMapper.insertSelective(userInfo);
                params.put("userId", userInfo.getUserId());
                userId = userInfo.getUserId();
            }

            couponList = couponUsrRelMapper.selectByMaps(params);
            //校验是否领过券
            for (TCouponUsrRel couponMap : couponList) {
                Integer useId = couponMap.getUserId();
                if (userId.equals(useId)) {
                    data.setCodeEnum(CodeEnum.CODE_60011);
                    return data;
                }
            }
            TCouponUsrRel couponUsrRel = new TCouponUsrRel();
            couponUsrRel.setUserId(userId);
            couponUsrRel.setIsUsed(0);
            couponUsrRel.setCouponId(couponId);
            couponUsrRel.setCreateTime(new Date());
            try {
                couponUsrRel.setUseTime(DateUtils.parse(DateUtils.addDay(new Date(), Integer.parseInt(discountCardInfo.getValidDay())), DateUtils.YYYY_MM_DD));
                couponUsrRel.setCardType(discountCardInfo.getCardType());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            couponUsrRelMapper.insertSelective(couponUsrRel);
        } else {
            data.setCodeEnum(CodeEnum.CODE_60010);
            return data;
        }

        return data;
    }

    /**
     * 查询未领券的用户列表
     *
     * @param params
     * @return
     */
    @Override
    public List<Map<String, Object>> selectUnUseCouponList(Map<String, Object> params) {
        return userInfoMapper.selectUnUseCouponList(params);
    }

    /**
     * 新增推拿服务
     *
     * @param serviceInfo
     * @return
     */
    @Override
    public Integer saveServiceInfo(InitServiceInfo serviceInfo) {
        return initServiceInfoMapper.insertSelective(serviceInfo);
    }

    /**
     * 查询推拿服务
     *
     * @return
     */
    @Override
    public InitServiceInfo selectServiceInfo(Integer serviceId) {
        return initServiceInfoMapper.selectByPrimaryKey(serviceId);
    }

    /**
     * 修改推拿服务
     *
     * @param serviceInfo
     * @return
     */
    @Override
    public Integer updateServiceInfo(InitServiceInfo serviceInfo) {
        return initServiceInfoMapper.updateByPrimaryKeySelective(serviceInfo);
    }

    /**
     * 新增商品 || 药品
     *
     * @param goodsInfo
     * @return
     */
    @Override
    public Integer saveGoodsInfo(InitGoodsInfo goodsInfo) {
        return initGoodsInfoMapper.insertSelective(goodsInfo);
    }

    /**
     * 新增商品 || 药品
     *
     * @return
     */
    @Override
    public InitGoodsInfo selectGoodsInfo(Integer goodsId) {
        return initGoodsInfoMapper.selectByPrimaryKey(goodsId);
    }

    /**
     * 修改商品 || 药品
     *
     * @param goodsInfo
     * @return
     */
    @Override
    public Integer updateGoodsInfo(InitGoodsInfo goodsInfo) {
        return initGoodsInfoMapper.updateByPrimaryKeySelective(goodsInfo);
    }

    /**
     * 新增门店信息
     *
     * @param subclinicInfo
     * @return
     */
    @Override
    public Integer saveSubclinic(TSubclinicInfo subclinicInfo) {
        return subclinicInfoMapper.insertSelective(subclinicInfo);
    }

    /**
     * 查询退卡
     *
     * @param backcardInfo
     */
    @Override
    public Map<String, Object> selectBackCardInfo(TBackcardInfo backcardInfo) {

        Map<String, Object> params = new HashMap<>();
        params.put("applyUserId", backcardInfo.getApplyUserId());
        params.put("isBack", 0);

        List<TBackcardInfo> backList = backcardInfoMapper.selectByMapList(params);
        if (backList.size() > 0) {
            return null;
        }

        params.put("userId", backcardInfo.getApplyUserId());
        params.put("subclinicId", backcardInfo.getSubclinicId());
        params.put("cardType", 2);
        List<AccountUserInfo> accountUserInfo = accountUserInfoMapper.selectByMap(params);

        boolean flag = false;
        Integer userId = 0;
        String userName = "", userPhone = "", subclinicName = "";
        if (accountUserInfo.size() > 0) {
            if (accountUserInfo.get(0).getSubclinicId() == backcardInfo.getSubclinicId()) {
                userId = accountUserInfo.get(0).getUserId();
                flag = true;
            }
            TSubclinicInfo subclinicInfo = subclinicInfoMapper.selectByPrimaryKey(accountUserInfo.get(0).getSubclinicId());

            if (ObjUtils.isNotEmpty(subclinicInfo)) {
                subclinicName = subclinicInfo.getSubclinicName();
            }

        }
        params.put("subclinicId", null);
        List<TUserInfo> userInfo = userInfoMapper.selectByMap(params);


        Map<String, Object> retMap = new HashMap<>();

        if (userInfo.size() > 0) {

            if (userInfo.get(0).getUserAccount().intValue() < 1) {
                return null;
            }

            userName = userInfo.get(0).getUserName();
            userPhone = userInfo.get(0).getUserPhone();
            retMap.put("userAccount", userInfo.get(0).getUserAccount());
        } else {
            retMap.put("userAccount", null);
        }

        retMap.put("userPhone", userPhone);

        retMap.put("userName", userName);
        retMap.put("subclinicName", subclinicName);
        retMap.put("userId", userId);
        retMap.put("subclinicId", backcardInfo.getSubclinicId());
        retMap.put("flag", flag);
        return retMap;
    }

    /**
     * 查询退款列表
     *
     * @param params
     * @return
     */
    @Override
    public List<TBackcardInfo> selectBackCardInfoList(Map<String, Object> params) {
        params.put("isBack", 0);
        List<TBackcardInfo> backList = backcardInfoMapper.selectByMapList(params);

        return backList;
    }

    /**
     * 修改门店信息
     *
     * @param subclinicInfo
     * @return
     */
    @Override
    public Integer updateSubclinic(TSubclinicInfo subclinicInfo) {
        return subclinicInfoMapper.updateByPrimaryKeySelective(subclinicInfo);
    }

    /**
     * 查询诊断结论列表
     *
     * @return
     */
    @Override
    public List<InitConclusionInfo> selectInitConclusionList() {
        return conclusionInfoMapper.selectByMap();
    }

    /**
     * 添加退款
     *
     * @param backcardInfo
     */
    @Override
    public Integer saveBackCardInfo(TBackcardInfo backcardInfo) {

        Map<String, Object> params = new HashMap<>();
        params.put("applyUserId", backcardInfo.getApplyUserId());
        params.put("isBack", 0);
        params.put("subclinicId", backcardInfo.getSubclinicId());

        List<TBackcardInfo> backList = backcardInfoMapper.selectByMapList(params);

        if (backList.size() > 0) {
            return 0;
        }

        //生成退款账务流水
        AccountUserInfo accountUserInfo = new AccountUserInfo();
        accountUserInfo.setCashierId(backcardInfo.getUserId());
        //类型：0:消费;1:充值;
        accountUserInfo.setAccountType(0);
        //类型：0:余额;1:次卡;2:储值
        accountUserInfo.setCardType(0);
        accountUserInfo.setSubclinicId(backcardInfo.getSubclinicId());
        accountUserInfo.setUserId(backcardInfo.getApplyUserId());
        accountUserInfo.setAccountCost(backcardInfo.getBackAccount());
        accountUserInfo.setAccountDesc("退款");
        accountUserInfo.setCreateTime(new Date());
        accountUserInfo.setBalancePayCost(backcardInfo.getBackAccount());
        accountUserInfo.setDoctorId(backcardInfo.getUserId());
        //支付方式:0:余额;1:支付宝二维码;2:微信二维码;3:现金;4:信用卡;5:次卡
        accountUserInfo.setPayWay(0);
        accountUserInfo.setAccountNo(ObjUtils.getAccountNo());
        accountUserInfoMapper.insertSelective(accountUserInfo);

        return backcardInfoMapper.insertSelective(backcardInfo);
    }

    // TreeJohn 导入丁香云余额忘记添加流水，补上流水
    @Override
    public void importExcelAccount() throws Exception {
        Map<String, Object> params = new HashMap<>();
        List<TUserInfo> userList = userInfoMapper.selectByMap(params);

        int importCount = 0;

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date importDate = sdf.parse("2018-07-30 20:30:00");

        for (TUserInfo user : userList) {
            if (user.getUserAccount().doubleValue() <= 0) {
                continue;
            }

            AccountUserInfo accountUserInfo = new AccountUserInfo();
            accountUserInfo.setCashierId(1); // 超级管理员
            //类型：0:消费;1:充值;
            accountUserInfo.setAccountType(1);
            //类型：0:余额;1:次卡;2:储值
            accountUserInfo.setCardType(0);
            accountUserInfo.setSubclinicId(user.getSubclinicId());
            accountUserInfo.setUserId(user.getUserId());
            accountUserInfo.setAccountCost(user.getUserAccount());
            accountUserInfo.setAccountDesc("导入丁香云余额");
            accountUserInfo.setCreateTime(importDate);
            accountUserInfo.setBalancePayCost(user.getUserAccount());
            accountUserInfo.setDoctorId(1); // 超级管理员
            //支付方式:0:余额;1:支付宝二维码;2:微信二维码;3:现金;4:信用卡;5:次卡
            accountUserInfo.setPayWay(0);
            accountUserInfo.setAccountNo(ObjUtils.getAccountNo());
            accountUserInfoMapper.insertSelective(accountUserInfo);
            importCount++;
        }

//        Log.info("importCount: " + importCount);

//        //生成退款账务流水
//        AccountUserInfo accountUserInfo = new AccountUserInfo();
//        accountUserInfo.setCashierId(backcardInfo.getUserId());
//        //类型：0:消费;1:充值;
//        accountUserInfo.setAccountType(0);
//        //类型：0:余额;1:次卡;2:储值
//        accountUserInfo.setCardType(0);
//        accountUserInfo.setSubclinicId(backcardInfo.getSubclinicId());
//        accountUserInfo.setUserId(backcardInfo.getApplyUserId());
//        accountUserInfo.setAccountCost(backcardInfo.getBackAccount());
//        accountUserInfo.setAccountDesc("退款");
//        accountUserInfo.setCreateTime(new Date());
//        accountUserInfo.setBalancePayCost(backcardInfo.getBackAccount());
//        accountUserInfo.setDoctorId(backcardInfo.getUserId());
//        //支付方式:0:余额;1:支付宝二维码;2:微信二维码;3:现金;4:信用卡;5:次卡
//        accountUserInfo.setPayWay(0);
//        accountUserInfo.setAccountNo(ObjUtils.getAccountNo());
//        accountUserInfoMapper.insertSelective(accountUserInfo);
    }

    /**
     * 修改退卡记录
     *
     * @param params
     */
    @Override
    public Integer updateBackCardInfo(Map<String, Object> params) {


        List<TBackcardInfo> backcardList = backcardInfoMapper.selectByMapList(params);

        if (backcardList.size() > 0 && backcardList.get(0).getIsBack() == 0) {
            backcardList.get(0).setIsBack(1);
            backcardInfoMapper.updateByPrimaryKeySelective(backcardList.get(0));

            TUserInfo userInfo = userInfoMapper.selectByPrimaryKey(backcardList.get(0).getApplyUserId());

            if (ObjUtils.isNotEmpty(userInfo)) {
                userInfo.setUserAccount(userInfo.getUserAccount().subtract(backcardList.get(0).getBackAccount()));
                userInfoMapper.updateByPrimaryKeySelective(userInfo);
            }
        } else {
            return 1;
        }
        return 0;
    }

    /**
     * 查询商品消耗列表
     *
     * @param subclinicId
     * @param ifMonth
     * @param orderTime
     * @return
     */
    @Override
    public List<Map<String, Object>> selectGoodsList(int subclinicId, int ifMonth, String orderTime) {
        Map<String, Object> prams = new HashMap<>();
        prams.put("subclinicId", subclinicId);
        if (ifMonth == 0 && orderTime != null) {
            prams.put("createTime", orderTime);
        } else if (ifMonth == 1 && orderTime != null) {
            prams.put("orderDate", orderTime);
        }
        return orderGoodsDetailMapper.selectOrderListByMap(prams);
    }

    /**
     * 查询商品消耗列表详情
     *
     * @param subclinicId
     * @param ifMonth
     * @param orderTime
     * @return
     */
    @Override
    public List<Map<String, Object>> selectGoodsListDetail(int subclinicId, int ifMonth, String orderTime) {
        Map<String, Object> prams = new HashMap<>();
        prams.put("subclinicId", subclinicId);
        if (ifMonth == 0 && orderTime != null) {
            prams.put("createTime", orderTime);
        } else if (ifMonth == 1 && orderTime != null) {
            prams.put("orderTime", orderTime);
        }
        return orderGoodsDetailMapper.selectSaleList(prams);
    }

    /**
     * 设置店长
     *
     * @param subclinicId
     * @param ownerId
     * @return
     */
    @Override
    public int updateOwner(int subclinicId, int ownerId) {
        Map<String, Object> prams = new HashMap<>();
        prams.put("subclinicId", subclinicId);
        prams.put("ownerId", ownerId);
        return subclinicInfoMapper.updateOwner(prams);
    }

    @Override
    public List<InitGradeDoctor> selectDoctorGradeList() {
        return gradeDoctorMapper.selectAll();
    }

    /**
     * 查询卡项列表
     *
     * @param params
     * @return
     */
    @Override
    public List<Map<String, Object>> selectAccountList(Map<String, Object> params) {

        Object cardType = params.get("cardType");
        Object dayType = params.get("dayType");

        if (ObjUtils.isEmpty(cardType)) {
            params.put("cardType", 0);
        }

        List<Map<String, Object>> accountList = new ArrayList<>();

        if (ObjUtils.isNotEmpty(dayType)) {
            if (dayType.equals("1")) {
                //今天
                params.put("nowDate", new Date());
            }
            if (dayType.equals("2")) {
                //近3天
                params.put("startDate", DateUtils.addDay(new Date(), -3));
                params.put("endDate", new Date());
            }
            if (dayType.equals("3")) {
                //近7天
                params.put("startDate", DateUtils.addDay(new Date(), -7));
                params.put("endDate", new Date());
            }
        }

        accountList = accountCardInfoMapper.selectAccountList(params);

        return accountList;
    }

    /**
     * 查询过期预约单号
     *
     * @return
     */
    @Override
    public List<TBookingInfo> selectOverBooking(Map<String, Object> params) {
        return bookingInfoMapper.selectOverBooking(params);
    }


    /**
     * 查询过期病历
     *
     * @return
     */
    @Override
    public List<TPatientTreatment> selectOverTreatment(Map<String, Object> params) {
        return patientTreatmentMapper.selectOverTreatment(params);
    }

    /**
     * 更新过期预约单号
     *
     * @param bookingInfo
     * @return
     */
    @Override
    public Integer updateBookingInfo(TBookingInfo bookingInfo) {
        return bookingInfoMapper.updateByPrimaryKeySelective(bookingInfo);
    }

    /**
     * 更新过期预约单号
     *
     * @param treatment
     * @return
     */
    @Override
    public Integer updateTreatment(TPatientTreatment treatment) {
        return patientTreatmentMapper.updateByPrimaryKeySelective(treatment);
    }

    /**
     * 获取用户来源
     *
     * @return
     */
    @Override
    public List<InitFromInfo> selectInitFromAll() {
        return initFromInfoMapper.selectAll();
    }

    /**
     * 获取标签
     *
     * @return
     */
    @Override
    public List<InitLabelInfo> selectInitLabelAll(Map<String, Object> params) {

        return labelInfoMapper.selectByMap(params);
    }

    @Override
    public void addUserCodeItem(UserCode userCode) {
        userCodeMapper.addItem(userCode);
    }

    @Override
    public Integer deletePatientInfo(Integer patientId) {
        TPatientInfo patientInfo = patientInfoMapper.selectByPrimaryKey(patientId);
        if (ObjUtils.isEmpty(patientInfo)) {
            return 1; // 宝宝不存在
        }

        // 查询是否有已完成订单
        Map<String, Object> stateParams = new HashMap<>();
        stateParams.put("patientId", patientId);
        stateParams.put("orderState", 0);
        List<TOrderInfo> orderList = orderInfoMapper.selectByMaps(stateParams);
        if (orderList.size() > 0) {
            return 2; // 有已完成订单
        }

        Map<String, Object> params = new HashMap<>();
        params.put("patientId", patientId);

        // 删除病历相关
        patientHistoryMapper.deleteByPatientId(patientId); // 删除病史档案
        userConclusionRelMapper.deleteByPatientId(patientId); // 删除诊断结论
        userDiseaseRelMapper.deleteByPatientId(patientId); // 删除用户病状
        userPointRelMapper.deleteByPatientId(patientId); // 删除用户穴位

        // 删除病历
        List<TPatientTreatment> patientTreatments = patientTreatmentMapper.selectByPatientId(params);
        for (TPatientTreatment treatment : patientTreatments) {
            Integer treatmentId = treatment.getTreatmentId();
            userTreatmentRelMapper.deleteByTreatmentId(treatmentId); // 删除病历得分
            patientTreatmentMapper.deleteByPrimaryKey(treatmentId);
        }

        // 删除用户订单相关
        List<TOrderInfo> orderInfos = orderInfoMapper.selectByMaps(params);
        for (TOrderInfo orderInfo : orderInfos) { // （by orderID)
            Integer orderId = orderInfo.getOrderId();
            accountOrderInfoMapper.deleteByOrderId(orderId); // 删除订单流水
            accountUserInfoMapper.deleteByOrderId(orderId); // 删除账户流水
            params.put("orderId", orderId);
            goodsDetailMapper.deleteByMap(params); // 删除商品详情
            serviceDetailMapper.deleteByMap(params); // 删除服务详情
        }
        orderInfoMapper.deleteByPatientId(patientId); // 删除订单

        // 删除预约
        bookingInfoMapper.deleteByPatientId(patientId);

        // 删除患者
        patientInfoMapper.deleteByPrimaryKey(patientId);
        patientInitMapper.deleteByPatientId(patientId);

        return 0;
    }

    @Override
    public Integer deleteUserCardInfo(Integer relId) {
        TCardUsrRel rel = cardUsrRelMapper.selectByPrimaryKey(relId);
        Integer leftCount = rel.getCardLeftTime();

        SysAccountCardInfo cardInfo = accountCardInfoMapper.selectByPrimaryKey(rel.getCardId());
        Integer totalCount = cardInfo.getCardCount();

        if (leftCount < totalCount) {
            return 1;
        }

        cardUsrRelMapper.deleteByPrimaryKey(relId);

        Map<String, Object> params = new HashMap<>();
        params.put("userId", rel.getUserId());
        params.put("cardId", rel.getCardId());
        params.put("createTime", rel.getCreateTime());
        accountUserInfoMapper.deleteByCardMap(params);

        return 0;
    }
}
